package com.su.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.su.common.utils.R;
import com.su.gulimall.cart.feign.ProductFeignService;
import com.su.gulimall.cart.interceptor.CartInterceptor;
import com.su.gulimall.cart.service.CartService;
import com.su.gulimall.cart.vo.Cart;
import com.su.gulimall.cart.vo.CartItem;
import com.su.gulimall.cart.vo.SkuInfoVo;
import com.su.gulimall.cart.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    private final String CART_PREFIX="gulimall:cart:";
    @Override
    public void addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> ops = getCartOps();

        //添加已经存在于购物车的商品
        String res = (String) ops.get("" + skuId);
        if(res!=null)
        {
            //从redis中获取商品信息，并修改商品的数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            //修改后的数据重新放回去
            ops.put(skuId.toString(),JSON.toJSONString(cartItem));
        }
        //购物车无此商品，添加新商品
        else {

            CartItem item = new CartItem();
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //第一，远程查询商品信息
                R r = productFeignService.info(skuId);
                //获取到远程信息
                SkuInfoVo skuInfo = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                item.setCheck(true);
                item.setCount(num);
                item.setSkuId(skuId);
                item.setImage(skuInfo.getSkuDefaultImg());
                item.setPrice(skuInfo.getPrice());
                item.setTitle(skuInfo.getSkuTitle());
            }, executor);
            CompletableFuture<Void> saleAttrsFuture = CompletableFuture.runAsync(() -> {
                //第二，远程查询组合信息
                List<String> attrValue = productFeignService.getSkuSaleAttrValue(skuId);
                item.setSkuAttr(attrValue);
            }, executor);
            //当两个异步任务都完成时，才执行下一步的操作
            CompletableFuture.allOf(getSkuInfoFuture,saleAttrsFuture).get();

            //第三，操作redis数据库，对购物车进行add操作
            //为了在redis中方便识别，避免jdk序列化，将购物项转换为一个json数据
            String s = JSON.toJSONString(item);
            ops.put(skuId.toString(),s);
        }


    }
    //获取购物车的某个购物项
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String s = (String) ops.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }
    //获取整个购物车
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //区分用户状态
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        if(userInfoVo.getUserId()!=null) {
            //1.登录
            String cartKey = CART_PREFIX+userInfoVo.getUserId();
            String tempCartKey= CART_PREFIX + userInfoVo.getUserKey();
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
            //2.需要判断临时购物车是否有数据
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            //todo:分析集合的判断为空方法的存在意义
            if(tempCartItems!=null)
            {
                for (CartItem cartItem : tempCartItems) {
                    //将临时购物车的数据放入用户购物车
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                clear(tempCartKey);
            }
            //3.获取用户购物车数据(包含临时购物车数据)
            List<CartItem> items = getCartItems(cartKey);
            cart.setCarts(items);
        }
        else {
            //未登录,获取临时购物车
            String cartKey = CART_PREFIX+userInfoVo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setCarts(cartItems);
        }
        return cart;
    }
    //清空购物车
    @Override
    public void clear(String cartKey)
    {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(),s);
    }

    @Override
    public void itemNum(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(),s);
    }

    @Override
    public void delItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCheckedCartItem() {
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        //用户没有登录
        if(userInfoVo.getUserId()==null)
        {
            return null;
        }else {
            String cartKey=CART_PREFIX+userInfoVo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream()
                    .filter((item) -> item.getCheck())
                    .map(item->{
                        //查出最新价格
                        R r = productFeignService.getPrice(item.getSkuId());
                        String data = (String) r.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }

    }

    //获取要操作的购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //1.判断用户状态,生成购物车的key
        UserInfoVo userInfoVo = CartInterceptor.threadLocal.get();
        String cartKey="";
        if(userInfoVo.getUserId()!=null)
        {
            cartKey=CART_PREFIX+userInfoVo.getUserId();
        }else {
            cartKey=CART_PREFIX+userInfoVo.getUserKey();
        }
        //往购物车中存储相关购物项
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
    //根据购物车的key,获取该购物车中的每个购物项，并封装成list集合
    private List<CartItem> getCartItems(String cartKey){

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        //购物车中有数据
        if(values!=null && values.size()>0) {
            List<CartItem> cartItems = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        //购物车中没有数据
        return null;
    }
}
